import cn from 'classnames';
import PropTypes from 'prop-types';
import React from 'react';
import fetch from 'API/fetch';
import { withRouter } from 'react-router';
import RaskSelect from '../../../components/RaskSelect';
import Label from '../../../components/Label';
import { datetime } from '../../../../common/formatter';
import { Spin } from 'antd';

import PortChange from './PortChange';
import PortTrend from './PortTrend';
import DomainChange from './DomainChange';
import DomainTrend from './DomainTrend';
import s from './style.module.css';

function Asset({
	className,
	match: {
		params: { jobId },
	},
	assetId,
	result,
	prevResult,
}) {
	const [dateRask, setDateRask] = React.useState({ detectTime: 'last', detectType: 'last' });
	const [taskList, setTaskList] = React.useState([]);
	const [allData, setAllData] = React.useState({});
	const [loading, setLoading] = React.useState(false);

	const getdata = async ({
		Type = 'asset',
		range = 'range',
		startTime,
		endTime,
	}) => {
		if (!jobId || jobId === ':jobId') return false
		setLoading(true);
		let url = `/api/v2/repodatas/report-task?jobId=${jobId}&taskType=${Type}&range=${range}`;
		if (range === 'range') {
			url += `&startTime=${new Date(startTime).toISOString()}
			&endTime=${new Date(endTime).toISOString()}`;
		}
		const resp = await fetch(url, {
			method: 'GET',
		}).catch(err => {
			console.log(err);
		}).finally(() => {
			setLoading(false);
		});
		setAllData(resp.TaskData || {});
		const taskLt = (resp.TaskData || []).reduce(
			(res, task) => {
				const domainWarnings = (task?.result?.warnings || []).filter(
					w => w.category === 'subdomain'
				);
				const portWarnings = (task?.result?.warnings || []).filter(
					w => w.category !== 'subdomain'
				);
				res.subDomain.push({
					...task,
					result: { ...task?.result, warnings: domainWarnings },
				});
				res.port.push({
					...task,
					result: { ...task?.result, warnings: portWarnings },
				});
				return res;
			},
			{
				port: [],
				subDomain: [],
			}
		);
		setTaskList(taskLt);
		setLoading(false);
	};

	const handleDateRask = val => {
		setDateRask(val);
		const obj = {
			range: val.detectTime || 'range',
		};
		if (obj.range === 'range') {
			obj.startTime = val.dateRange[0];
			obj.endTime = val.dateRange[1];
		}
		getdata(obj);
	};

	const date =
		dateRask?.detectTime === 'last' ? result?.endTime : prevResult?.endTime;
	React.useMemo(() => {
		getdata({ range: 'last' });
	}, [assetId]);
	return (
		<Spin spinning={loading}>
			<div className={cn(className, s.asset)}>
				<div className={s.head}>
					<div className={s.title}>
						<Label className={s.label}>资产变动</Label>
						{dateRask?.detectTime && (
							<span className={s.time}>{datetime(date)}</span>
						)}
					</div>
					<RaskSelect
						value={dateRask}
						onChange={handleDateRask}
						resultLength={allData?.length || 0}
					/>
				</div>
				<DomainTrend
					detectTime={dateRask?.detectTime}
					tasks={taskList?.subDomain || []}
					dateRask={dateRask}
					jobId={jobId}
				/>
				<DomainChange
					tasks={taskList?.subDomain || []}
					result={result}
					prevResult={prevResult}
					detectTime={dateRask?.detectTime}
				/>
				<PortTrend
					detectTime={dateRask?.detectTime}
					tasks={taskList?.port || []}
					jobId={jobId}
				/>
				<PortChange
					tasks={taskList?.port || []}
					result={result}
					prevResult={prevResult}
					detectTime={dateRask?.detectTime}
				/>
			</div>
		</Spin>
	);
}

Asset.propTypes = {
	className: PropTypes.string,
	match: PropTypes.shape({
		params: PropTypes.shape({
			jobId: PropTypes.string,
		}),
	}),
	assetId: PropTypes.string,
	result: PropTypes.shape({
		endTime: PropTypes.object,
		target: PropTypes.string,
		result: PropTypes.shape({
			warningCount: PropTypes.number,
			warnings: PropTypes.shape({
				category: PropTypes.string,
				affects: PropTypes.string,
				detail: PropTypes.object,
			}),
		}),
	}),
	prevResult: PropTypes.shape({
		endTime: PropTypes.object,
		target: PropTypes.string,
		result: PropTypes.shape({
			warningCount: PropTypes.number,
			warnings: PropTypes.shape({
				category: PropTypes.string,
				affects: PropTypes.string,
				detail: PropTypes.object,
			}),
		}),
	}),
};
Asset.defaultProps = {
	className: '',
};

export default withRouter(Asset);
